package my2Cents.tools;

import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.util.Random;

import my2Cents.BodyState;
import my2Cents.Sandbox;
import my2Cents.Undo;
import my2Cents.Util;
import net.phys2d.math.Vector2f;
import net.phys2d.raw.shapes.PhysShape;

public class RemoverTool extends MoverTool {
	private PhysShape shape;
	private Vector2f position;
	private float rotation;
	private AffineTransform ghostTransform = new AffineTransform();
	
	public RemoverTool() {
		setGhostColor(AbstractPhysTool.GHOSTCOLOR_REMOVE);
		setDescription(
				"Click on an object to remove it."
			);
	}
	
	public void startTool(MouseEvent arg0) {
		osize = 20;
		this.setGhostOutlineSize(osize);
		currentBody = Util.selectBody(arg0.getX(), arg0.getY(), getWorld());
		if(currentBody == null) {
			endTool(arg0);
			return;
		}
		if(currentBody.getShape() != null) {
			shape = currentBody.getShape();
		}
		position = (Vector2f) currentBody.getPosition();
		rotation = currentBody.getRotation();
		
		ghostTransform = new AffineTransform();
		ghostTransform.setToTranslation(position.x,position.y);
		ghostTransform.translate(ghostOffset.x, ghostOffset.y);
		
		getWorld().getBodyStateManager().purgeBodyState(Sandbox.BODYSTATES_SANDBOX, currentBody);
		
		Undo finalUndo = Sandbox.getUndoList().getUndo(currentBody, null);
		if(finalUndo != null) {
			finalUndo.performUndo();
		} else {
			getWorld().remove(currentBody);
		}

		currentBody = null;
		endTool(arg0);
	}
	
	public boolean canDraw() {
		return (this.getGhostOutlineSize() > 1 && shape != null);
	}
	
	public void drawGhost(Graphics2D g) {
		if(this.getGhostOutlineSize() <= 1) {
			shape = null;
		}
		super.drawGhost(g);
	}
	
	public GeneralPath getGhostPath() {
		Random r = new Random();
		if(shape != null) {
			GeneralPath gp = shape.getGeneralPath(new Vector2f(0,0),rotation);
			ghostTransform.scale(0.95,0.95);
			gp.transform(ghostTransform);
		return gp;
		}
		return new GeneralPath();
	}
	
	public void toolThink(MouseEvent arg0) {
		Random r = new Random();
		if(position != null) {
			rotation += r.nextFloat()-.5;
			ghostTransform.translate(r.nextInt(10)-5,r.nextInt(10)-5);
		}
	}

}
